package org.bonorsoft.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.bonorsoft.common.util.StringUtils;
import org.bonorsoft.modules.user.entity.MobileUserRole;
import org.bonorsoft.modules.user.mapper.MobileUserRoleMapper;
import org.bonorsoft.modules.user.service.IMobileUserRoleService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class IMobileUserRoleServiceImpl extends ServiceImpl<MobileUserRoleMapper, MobileUserRole> implements IMobileUserRoleService {

    @Override
    public void addUserRole(List<String> userIdList, List<Integer> labelIdList) {
        labelIdList.forEach(item -> userIdList.forEach( it -> {
            deleteRole(item, it);
            MobileUserRole userRole = new MobileUserRole();
            userRole.setUserId(it);
            userRole.setId(item);
            this.save(userRole);
        }));
    }

    @Override
    public void deleteUserRole(List<String> userIdList, List<Integer> labelIdList) {
        labelIdList.forEach(item -> userIdList.forEach( it -> deleteRole(item, it)));
    }

    private void deleteRole(Integer roleId, String userId){
        QueryWrapper<MobileUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USER_ID",userId).eq("id", roleId);
        this.remove(queryWrapper);
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param id 角色ID
     * @return 结果
     */
    public Integer countUserRoleByRoleId(Integer id) {
        QueryWrapper<MobileUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return this.count(queryWrapper);
    }

    /**
     * 新增用户与角色管理
     * @param id
     * @param roleIds
     */
    @Override
    public void insertUserRole(String id, Integer[] roleIds) {
        if (StringUtils.isNotNull(roleIds))
        {
            List<MobileUserRole> list = new ArrayList<>();
            for (Integer roleId : roleIds)
            {
                MobileUserRole ur = new MobileUserRole();
                ur.setUserId(id);
                ur.setId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                this.saveBatch(list);
            }
        }
    }

    /**
     * 删除用户与角色关联
     * @param id 用户id
     */
    @Override
    public void deleteUserRoleByUserId(String id) {
        this.remove(new QueryWrapper<MobileUserRole>().eq("user_id", id));
    }

    /**
     * 通过用户ID查询用户和角色关联
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<MobileUserRole> selectUserRoleByUserId(String userId) {
        return this.list(new QueryWrapper<MobileUserRole>().eq("user_id", userId));
    }
}
